import {_decorator, Component, Node, Label} from 'cc';

const {ccclass, property} = _decorator;

@ccclass('SocketController')
export class SocketController extends Component {

    private ws: WebSocket = null;

    start() {
        // 创建WebSocket
        this.ws = new WebSocket("ws://localhost:8080/api/websocket/1");
        // onopen
        this.ws.onopen = (ev) => {
            console.log("onopen：" + JSON.stringify(ev));
        };
        // onmessage
        this.ws.onmessage = (ev) => {
            this.node.getComponent(Label).string = ev.data;
            console.log("onmessage：" + JSON.stringify(ev));
        };
        // onclose
        this.ws.onclose = (ev) => {
            console.log("onclose：" + JSON.stringify(ev));
        };
        // onerror
        this.ws.onerror = (ev) => {
            console.log("onerror：" + JSON.stringify(ev));
        };
    }

    update(deltaTime: number) {

    }

    /**
     * 发送消息
     *
     * @param message 消息
     */
    send(message: string) {
        this.ws.send(message);
    }
}

